package hzau.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSON;
import hzau.constants.WeChatConstant;
import hzau.pojo.User;
import hzau.pojo.WeChatUser;
import hzau.result.Result;
import hzau.service.LoginService;
import hzau.utils.CodeUtil;
import hzau.utils.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;

@CrossOrigin
@RestController
@ResponseBody
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("user/login")
    public Result login(@RequestBody User user){
        return loginService.login(user);
    }

    //TODO 实现微信登录
    @PostMapping("user/loginWeChat")
    public Result  loginWeChat()throws Exception{
        String state = UUID.randomUUID().toString();

        //编码回调地址
        String redirectUrl= URLEncoder.encode("http://6f9f164e.r10.cpolar.top/wechatCallback","UTF-8");
        //构造二维码的链接地址
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ WeChatConstant.APPID +"&redirect_uri=" +redirectUrl
                +"&response_type=code&scope=snsapi_userinfo&state="+state+"#wechat_redirect";
        //生成二维码，扫描后跳转到上面的地址
        String s = CodeUtil.QrGenerate(url);
        HashMap<String,String> res=new HashMap<>();
        res.put("url",s);
        res.put("state",state);
        return Result.success(res);
    }
    @GetMapping("wechatCallback")
    public String wechatCallback(String code, String state, HttpServletRequest request, HttpServletResponse response,
                                 HttpSession session)throws  Exception{
//        redisTemplate.opsForValue().set(state,1);
        WeChatUser user= WeChatUtil.getUserInfo(code);
        redisTemplate.opsForValue().set(state,user.getOpenid());

        return JSON.toJSONString(user);
    }
    @GetMapping("wechat")
    public String wechat(
            @RequestParam(value = "signature") String signature,
            @RequestParam(value = "timestamp") String timestamp,
            @RequestParam(value = "nonce") String nonce,
            @RequestParam(value = "echostr") String echostr

            ){
        return echostr;
    }
    @GetMapping("/weChat/getState/{state}")
    public Result getWechatState(@PathVariable String state){
        Object o = redisTemplate.opsForValue().get(state);
        if (o!=null){
            String wechatId=o.toString();
            return loginService.weChatLogin(wechatId);
        }else {
            return Result.error(1000,"微信还未登录");
        }
    }
    @GetMapping("/user/logout")
    public Result logout(){
        return loginService.logout();
    }

    @PostMapping("/user/register")
    public Result register(String userName,String password){
        return loginService.register(userName,password);
    }
    @PostMapping("/turnBack")
    public Result turnBack(@RequestBody Result result){
        return result;
    }
}
